package com.per.mybootall.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.Serializable;

/*
* 通用的用泛型构造的服务端响应对象----->把它序列化返回给前端
* */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
                                    /*
                                    @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
                                    *   private ServerResponse(int status) {
                                            this.status = status;
                                        例如这种情况，不需要返回msg和data时，序列化后就不会有msg和data(保证序列化json的
                                                                                 时候，如果是null的对象，key也会消失)
                                    * */
public class ServerResponse<T> implements Serializable {
    private int status;
    private String msg;
    //泛型的数据对象
    private T data;
    private ServerResponse(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    private ServerResponse(int status, T data) {
        this.status = status;
        this.data = data;
    }
    private ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }
    private ServerResponse(int status) {
        this.status = status;
    }

    public ServerResponse(String errorMessage) {
    }

    @JsonIgnore
    //使之不在json序列化结果当中
    public boolean isSuccess(){
            return this.status==ResponseCode.SUCCESS.getCode();
    }
    public int getStatus(){
            return status;
    }
    public T getdata(){
            return data;
    }

    public String getmsg(){
        return msg;
    }
    public static <T> ServerResponse<T> creatBySuccess(){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }
    public static <T> ServerResponse<T> creatBySuccessMessage(String msg){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
    public static <T> ServerResponse<T> creatBySuccess(T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
    }
    public static <T> ServerResponse<T> creatBySuccess(String msg,T data){
        return new ServerResponse<>(ResponseCode.SUCCESS.getCode(),msg,data);
    }
    //失败的情况
    public static <T> ServerResponse<T> creatByError(){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
    }
    public static <T> ServerResponse<T> creatByErrorMessgae(String errorMessage){
        return new ServerResponse<T>(errorMessage);
    }
    public static <T> ServerResponse<T> creatByErrorCodeMessgae(int errorCode,String errorMessage){
        return new ServerResponse<T>(errorCode,errorMessage);
    }
}
